import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
import {
  getAblumNewest,
  getArtistList,
  getBanners,
  getRankingData,
  getRecommend
} from '../service/recommend'
export const fetchRecommendDataAction = createAsyncThunk(
  'fetchdata',
  async (_, { dispatch }) => {
    getBanners().then((res) => {
      dispatch(changeBannersAction(res.banners))
    })

    // 热门推荐
    getRecommend().then((res) => {
      dispatch(changeHotRecommendsAction(res.result))
    })
    // 新碟上架
    getAblumNewest().then((res) => {
      dispatch(changeAlbumNewestAction(res.albums))
    })
    // 榜单：飙升榜 19723756 新歌榜 3779629 原创榜 2884035

    const rankingIds = [19723756, 3779629, 2884035]
    // 1. 数据分开存
    // for (const id of rankingId) {
    //   getRankingData(id).then((res) => {
    //     // console.log(res.data.playlist.tracks)
    //     switch (id) {
    //       case 19723756:
    //         console.log('飙升榜：', res.data)
    //         break
    //       case 3779629:
    //         console.log('新歌榜：', res.data)
    //         break
    //       case 2884035:
    //         console.log('原创榜：', res.data)
    //         break
    //     }
    //   })
    // }

    // 2. 数据存在一起
    // 2.1 获取到所有的结果后，进行dispatch操作
    // 2.2 获取到的结果，一定是有正确的顺序的
    const promises: Promise<any>[] = []
    for (const id of rankingIds) {
      promises.push(getRankingData(id))
    }
    Promise.all(promises).then((res) => {
      const playlists = res.map((item) => item.playlist)

      dispatch(changeRankingsAction(playlists))
    })

    getArtistList(5).then((res) => {
      dispatch(changeSettleSingsAction(res.artists))
    })
  }
)

export interface IRecommendState {
  banners: any[]
  hotRecommends: any[]
  albumNewest: any[]
  rankings: any[]
  // upRanking: any
  // newRanking: any
  // originRanking: any
  settleSingers: any[]
}
const initialState: IRecommendState = {
  banners: [],
  hotRecommends: [],
  albumNewest: [],
  rankings: [],
  settleSingers: []
}
const recommendSlice = createSlice({
  name: 'recommend',
  initialState,
  reducers: {
    changeBannersAction(state, { payload }) {
      state.banners = payload
    },
    changeHotRecommendsAction(state, { payload }) {
      state.hotRecommends = payload
    },
    changeAlbumNewestAction(state, { payload }) {
      state.albumNewest = payload
    },
    changeRankingsAction(state, { payload }) {
      state.rankings = payload
    },
    changeSettleSingsAction(state, { payload }) {
      state.settleSingers = payload
    }
  }
})
export const {
  changeBannersAction,
  changeHotRecommendsAction,
  changeAlbumNewestAction,
  changeRankingsAction,
  changeSettleSingsAction
} = recommendSlice.actions
export default recommendSlice.reducer
